const express = require('express')
const cors = require('cors')
const db = require('./db')
const flow = require('./tools/flow')
const integrationModules = require('./integrationModules')
const tool = require('./tools/tool')
const config = require('../config')
const multer = require('multer')
const bodyParser = require('body-parser')
// const settings = require('./methods/settings')
const runner = require('./runner')
const http = require('http')
const path = require('path')
const fs = require('fs')

const app = express();
app.use(express.json())
app.use(cors())

async function connectDataBase() {
    await db.init({
        host: '110.42.246.177',
        user: 'root',
        password: 'Catiouszty2004_',
        database: 'miniStorage',
        port: 3306,
        charset: 'utf8mb4'
    })
}

module.exports = {
    async start(port = 0, handleStarted = () => { }) {
        // const user = require('./methods/user')
        // 连接数据库
        console.clear()
        console.log('正在连接数据库...')
        if (await flow(connectDataBase, (error) => {
            console.clear()
            console.log('无法连接数据库，原因：', error)
        })) {
            console.clear()
            // 成功连接数据库

            // 数据库保活
            setInterval(() => {
                db.exe(`select id from users`, false)
            }, 1000 * 60);

            // 解析接口模块
            let parsedPorts = await integrationModules()
            // console.log(parsedPorts)
            for (let i = 0; i < parsedPorts.length; i++) {
                let c = parsedPorts[i]
                // console.log(config.apiPrefix + c.api)
                // console.log(c.api)
                app[c.method == 'get' ? 'get' : 'post'](config.apiPrefix + c.api, ...(() => {
                    if (c.middlewares instanceof Array) {
                        return c.middlewares
                    } else {
                        return []
                    }
                })(), async (req, res) => {
                    let token = req.headers.token
                    if (c.auth) {
                        try {
                            await tool.methods.user().checkToken(token, c.auth.admin === true)
                        } catch (error) {
                            res.send({
                                status: -1,
                                content: error.toString()
                            })
                            return
                        }
                    }
                    let data
                    try {
                        data = req.body
                    } catch (error) {
                        console.log(error)
                    }
                    try {
                        if (typeof (data) !== 'object') data = {}
                        // let usdt
                        // try {
                        //     usdt = (await user.getSingleUserInfoByOpenId(JSON.parse(tool.decodeString(token)).openId))
                        // } catch (error) {

                        // }
                        data = {
                            query: req.query,
                            param: data
                        }
                        // 到runner中执行
                        runner.add(c.func, res, req.headers, data, req, c.exp, c.method, c.auth)
                        return
                    } catch (error) {
                        console.log(error)
                        res.send({
                            status: 0,
                            content: tool.string.delete.bySubString(error.toString(), 'Error:')
                        })
                        return
                    }
                })
            }
            // 完成接口模块解析

            // 文件相关接口
            // const storage = multer.diskStorage({
            //     destination: 'files/',
            //     filename: function (req, file, cb) { 
            //         const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
            //         const fileExtension = path.extname(file.originalname);
            //         cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
            //     }
            // })
            // const upload = multer({ storage: storage })
            // app.post(config.apiPrefix + '/file/upload', upload.single('file'), async (req, res) => {
            //     if (!req.file) {
            //         res.status(400).json({ error: '上传失败' })
            //     } else {
            //         res.json({
            //             status: 1,
            //             content: '上传成功',
            //             data: req.file.filename
            //         })
            //     }
            // })
            // app.get(config.apiPrefix + '/file/download/:filename', async (req, res) => {
            //     const filename = req.params.filename;
            //     if (filename.indexOf('%b64%') != -1) {
            //         let re = await execSQL("select data from file where name = '" + filename + "'")
            //         if (re.length == 0) {
            //             res.send('')
            //             return
            //         }
            //         re = re[0].data
            //         res.setHeader('Content-Type', `image/jpeg`);
            //         res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
            //         res.send(re)
            //         return
            //     }


            //     const filePath = path.join(__dirname, '../files', filename);
            //     if (!fs.existsSync(filePath)) {
            //         return res.status(404).json({
            //             status: 0,
            //             content: '无此文件'
            //         });
            //     }
            //     res.setHeader('Content-Disposition', `filename=${filename}`);
            //     const fileStream = fs.createReadStream(filePath);
            //     fileStream.pipe(res);
            // })
            app.use(bodyParser.json({ limit: '50gb' }))
            app.use(bodyParser.raw({ type: 'text/xml' }));
            app.use(bodyParser.urlencoded({ limit: '50gb', extended: true }))
            const server = http.createServer(app)
            server.listen(port, handleStarted)
        }
    }
}